package com.fang.algorithm.leecode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author fanglingxiao
 * @version 1.0
 * @description 螺旋矩阵
 * 给你一个 m 行 n 列的矩阵 matrix ，请按照 顺时针螺旋顺序 ，返回矩阵中的所有元素。
 * 输入：matrix = [[1,2,3],[4,5,6],[7,8,9]]
 * 输出：[1,2,3,6,9,8,7,4,5]
 * <p>
 * 输入：matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
 * 输出：[1,2,3,4,8,12,11,10,9,5,6,7]
 * @date 2022/5/20 11:46 上午
 **/
public class L54_SpiralOrder {
    public static void main(String[] args) {
        int[][] matrix = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
        List<Integer> ans = spiralOrder(matrix);
        System.out.println(ans);
    }

    private static List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> ans = new ArrayList<>();
        if (null == matrix || matrix.length == 0 || matrix[0].length == 0) {
            return ans;
        }
        int left = 0;
        int right = matrix[0].length - 1;
        int top = 0;
        int high = matrix.length - 1;
        while (left <= right && top <= high) {
            // 从左到右
            for (int i = left; i <= right; i++) {
                ans.add(matrix[top][i]);
            }
            // 从上到下
            for (int i = top + 1; i <= high; i++) {
                ans.add(matrix[i][right]);
            }
            if (left < right && top < high) {
                // 从右到左
                for (int i = right - 1; i > left; i--) {
                    ans.add(matrix[high][i]);
                }
                // 从下到上
                for (int i = high; i > top; i--) {
                    ans.add(matrix[i][left]);
                }
            }
            top++;
            right--;
            high--;
            left++;
        }
        return ans;
    }
    public int minPathSum(int[][] grid) {
        int len = grid[0].length;
        int[] dp = new int[len];
        dp[0] = grid[0][0];
        for (int i = 1; i < len; i++)
            dp[i]=dp[i-1]+grid[0][i];
        for (int i = 1; i < grid.length; i++) {
            dp[0] = dp[0] + grid[i][0];
            for (int j = 1; j < len; j++)
                dp[j] = Math.min(dp[j-1]+grid[i][j], dp[j]+grid[i][j]);
        }
        return dp[len-1];
    }
}
